import React from 'react';
import {
	StyleSheet,
	View,
	Text,
	Image,
	TouchableOpacity,
	ScrollView,
	RefreshControl,
	Platform,
	BackHandler
} from 'react-native';
import {setSpText,setHW} from '../../component/ScreenUtil'
const Dimensions = require('Dimensions');
const { width,height } = Dimensions.get('window');
import MyCourseList from '../../component/MyCourseList'
import Loading from '../../common/Loading'
import { pageMyCourse,listParents } from '../../api/my'



var cacheData = {
	total: 0,
	nextPage: 1,
	items: []
}
export default class MyCourse extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			loading: true,
			COLLECTION: null,//收藏的数目
			FLLOW: null,//关心的数目
			totleNum: null,//总条数
			parentListId:[],
			dataList: [],
			isRefreshing: false,
			LessonsMore: false,
			isLoading: false
		}
		
	}
	// 获取我的课程
	componentDidMount() {
		// alert('1')
		this.setState({loading: true,dataList:[]})//不然会累加数据
		this._getlistData();
		
		// BackHandler.addEventListener('hardwareBackPress', function () { })

	}

	

	componentWillReceiveProps(){
		// alert('2')
		this.setState(
			{
				loading: true,
				COLLECTION: null,//收藏的数目
				FLLOW: null,//关心的数目
				totleNum: null,//总条数
				parentListId:[],
				dataList: [],
				isRefreshing: false,
				LessonsMore: false,
				isLoading: false
			}
		)//不然会累加数据
		cacheData = {
			total: 0,
			nextPage: 1,
			items: []
		}
		this._getlistData();
	}
	_getlistData(){
		let obj={
			STUDENTID:global.ECourseConstant.userInfo.studentId
		}
		listParents(obj).then((res)=>{
            this.setState({parentListId:res});//获取家长id数组
			this._pageMyCourse()
        });
	}
	_pageMyCourse(page) {
		let json = {
			"PAGE": page ? page : 1,
			"ROWS": setHW(20),
			"PAY_USER_ID": global.ECourseConstant.userInfo.uuid,
			"PARENTID": []//家长id数组
		}
		let userType = global.ECourseConstant.userInfo.loginType;
		// 如果是学生
		if (userType == '4') {
			json.PARENTID=this.state.parentListId
		}
		this.setState({
			isLoading: true
		})
		pageMyCourse(json).then(res => {
			global.log(res,'res-===我的课程')
			cacheData.items = this.state.dataList.concat(res.MYCOURSE.LIST);
			cacheData.total = res.MYCOURSE.PAGINATION.TOTAL;
			var data = [...cacheData.items]
			this.setState(
				{
					loading: false,
					COLLECTION: res.COLLECTION,//我的收藏的数量
					FLLOW: res.FLLOW,//我的关注的数量
					totleNum: res.MYCOURSE.PAGINATION.TOTAL,
					dataList: data,//我的课程的数据
					isLoading: false,
					isRefreshing: false
				}
			);
		})
	}
	
	// 跳转到我的收藏
	goMyCollect() {
		let that=this;
		this.props.navigation.navigate('MyCollection',{
			refreshPage: function () {
				that._refreshCoursePage();
			}
		});
		// console.log(this,'thisthithththththth')
		if (this.props&&this.props.navigation&&this.props.navigation.pressBack) {
			BackHandler.removeEventListener('hardwareBackPress', this.props.navigation.pressBack)
		}
		
	}
	// 跳转到我的关注
	MyCare() {
		let that=this;
		this.props.navigation.navigate('MyCare',{
			refreshPage: function () {
				that._refreshCoursePage();
			}
		});
		if (this.props&&this.props.navigation&&this.props.navigation.pressBack) {
			BackHandler.removeEventListener('hardwareBackPress', this.props.navigation.pressBack)
		}
	}
	_refreshCoursePage(){
		this.setState({dataList: [], loading:true});
		cacheData = {
			total: 0,
			nextPage: 1,
			items: []
		};
		this._pageMyCourse();
	}
	render() {
		return (
			<View style={styles.MyCourse}>
					<View>
						<TouchableOpacity style={[styles.myCollectCare, styles.myCollect]} onPress={() => this.goMyCollect()}>
							<Text style={styles.myText}>我的收藏</Text>
							<View style={styles.rightEnter}>
								<Text style={styles.num}>{this.state.COLLECTION}</Text>
								<Image style={styles.enterIcon} source={require('../../assets/imgs/enter.png')} />
							</View>
						</TouchableOpacity>
						<TouchableOpacity style={[styles.myCollectCare, styles.myCollect]} onPress={() => this.MyCare()}>
							<Text style={styles.myText}>我的关注</Text>
							<View style={styles.rightEnter}>
								<Text style={styles.num}>{this.state.FLLOW}</Text>
								<Image style={styles.enterIcon} source={require('../../assets/imgs/enter.png')} />
							</View>
						</TouchableOpacity>
						<Text style={styles.haveCourse}>我已报名的课程</Text>
					</View>
					<ScrollView 
						refreshControl={
							<RefreshControl
								refreshing={this.state.isRefreshing}
								onRefresh={this._onRefresh.bind(this)}
								tintColor="#FF8A00"
								// title="加载中..."
								titleColor="#ddd"
								colors={['#FF8A00']}
								progressBackgroundColor="#ffffff"
							/>
						}
						alwaysBounceVertical={false}
						onScroll={this._onScroll.bind(this)}
						showsVerticalScrollIndicator={false}
						scrollEventThrottle={20}>
						{this.state.dataList.length?<View style={styles.haveCourseListBox}>
							<MyCourseList myCourseIndex={true} 
							dataList={this.state.dataList} 
							ResetSearch={()=>this._refreshCoursePage()}
							{...this.props}></MyCourseList>
						</View>:null}
						{this.loadMore()}
						{/* {this.NoData()} */}
					</ScrollView>
			</View>
		);
	}
	// 刷新首页
	_onRefresh = () => {
		if(this.state.dataList.length){
			cacheData = {
				items: [],
				nextPage: 1,
				total: 0
			}
			this.setState({
				dataList: [], // 推荐课程数据
				isLoading: false,
				LessonsMore: false,
				isRefreshing: true
			})
			this._pageMyCourse(1);
		}
	}
	hasMoreLessons() {
		if (this.state.dataList.length == cacheData.total && cacheData.total > 0) {
			this.setState({
				LessonsMore: false
			})
			return false
		}
		return true
	}
	// 加载更多数据
	_onScroll = (event) => {
		// global.log(this.state.isLoading, !this.hasMoreLessons(), 'this.state.isLoading || !this.hasMoreLessons()')
		if (this.state.isLoading || !this.hasMoreLessons()) {
			return;
		}

		let y = event.nativeEvent.contentOffset.y;
		let height = event.nativeEvent.layoutMeasurement.height;
		let contentHeight = event.nativeEvent.contentSize.height;
		// 如果拖拽值超过底部50，且当前的scrollview高度大于屏幕高度，则加载更多
		const _num = contentHeight - height - y;
		// global.log('offsetY-->' + y);
		// global.log('height-->' + height);
		// global.log('contentHeight-->' + contentHeight);

		// android 实现方式
		if (Platform.OS == 'android' && (y + height >= contentHeight - 30)) {
			// console.log(121212,'contentHeight');
			this.loadMoreData();
		}
		// ios 实现方式
		else if (contentHeight > height && _num < -10) {
			this.loadMoreData()
		}
	}    


	loadMoreData() {
		this.setState({
			loadMore: true,
			isLoading: false
		}, () => {
			cacheData.nextPage = cacheData.nextPage + 1;
			this._pageMyCourse(cacheData.nextPage)
		});
	}
	// 正在加载or底部
	loadMore(){	
		if(this.state.isLoading){
			return(
				<View style={styles.loadMore}>
					<Text style={styles.loadMoreText}>正在加载中...</Text>
				</View>
			)
		}else {
			return(
				<View style={[styles.loadMore,this.state.dataList.length == 0?styles.noDataBackWhite:'']}>
					<Text style={styles.loadMoreText}>{this.state.dataList.length == 0 ? '暂无课程' : (this.state.dataList.length == cacheData.total ? '已经全部加载完毕' : '')}</Text>
				</View>
			)
		}
	}
}
const styles = StyleSheet.create({
	MyCourse: {
		flex: 1,
		backgroundColor: '#F7F7F9'
	},
	navigatorBar: {
		backgroundColor: '#fff'
	},
	haveCourseListBox:{
		backgroundColor:'#F7F7F9',
	},
	myCollectCare: {
		paddingLeft: setHW(20),
		paddingRight: setHW(20),
		backgroundColor: '#fff',
		marginBottom: 1,
		height:setHW(100),
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems:'center',
	},
	rightEnter: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
	},
	myText: {
		fontSize:setSpText(30),
		width: setHW(160),
		color: '#333',
	},
	num: {
		fontSize:setSpText(30),
		color: '#999',
		paddingRight: setHW(20),
	},
	enterIcon: {
		width: setHW(18),
		height: setHW(30),
	},
	haveCourse: {
		color: '#666666',
		fontSize:setSpText(24),
		paddingLeft: setHW(20),
		paddingBottom: setHW(10),
		paddingTop: setHW(20),
		backgroundColor:'#F7F7F9',
	},
	loadMore: {
		flexDirection: 'row',
		justifyContent: 'center',
		height: setHW(100),
		alignItems: 'center',
	},
	noDataBackWhite:{
		backgroundColor:'#fff',
		height:height - setHW(500),
	},
	loadMoreText: {
		color: '#ddd',
	}
})